<?php
/**
 * Created by zengxianfen on 2020/7/28 18:12.
 */

namespace App\Model\Service;


use App\Exception\ServiceException;
use App\Model\Repository\UserRepository;
use Hyperf\Config\Annotation\Value;
use Hyperf\Contract\SessionInterface;
use Hyperf\Di\Annotation\Inject;

class UserService extends BaseService
{
    /**
     * @Inject()
     * @var UserRepository
     */
    protected $repository;

    /**
     * @Value("password_salt")
     * @var string
     */
    protected $password_salt;


    /**
     * @Inject()
     * @var SessionInterface
     */
    protected $session;

    /**
     *
     * @author zengxianfen 2020/7/28
     * @param array $login
     * @return bool
     * @throws ServiceException
     */
    public function login(array $login) {
        $user = $this->repository->getModel();
        $exists = $user::query()->where(['name' => $login['name'], 'password' => md5($login['password'].$this->password_salt)])->first();
        if (empty($exists)) {
            throw new ServiceException("用户名或密码错误");
        }
        $this->session->set('user', $exists->jsonSerialize());
        return true;
    }
}